﻿using DataAccess;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System.Reflection;

namespace MyPetHub.Controllers
{
    public class BaseController : Controller
    {
        public IMemoryCache mcObj;
        public readonly MyPetHubContext dbContext;//dbContext.Database.SetCommandTimeout(TimeSpan.FromSeconds(5));
        public static Dictionary<long, string?>? speciesinfoDict;

        public string subDomain;
        public long merID;
        public List<string> allowedImgList = new List<string>() { ".jpg", ".jpeg", ".png" };
        public List<string> allowedVideoList = new List<string>() { ".mp4", ".avi", ".webm" };

        public BaseController(IMemoryCache mcObj, MyPetHubContext dbContext, IHttpContextAccessor httpContextAccessor) 
        {
            this.mcObj = mcObj;
            this.dbContext = dbContext;

            //二级域名，商家代号和id
            subDomain = httpContextAccessor.HttpContext.Request.Headers["MerchantCode"].ToString();
            merID = long.Parse(httpContextAccessor.HttpContext.Request.Headers["MerchantId"].ToString());

            //种类缓存数据
            if (mcObj.Get<Dictionary<long, string>>("speciesinfo") == null)
            {
                speciesinfoDict = dbContext.SpeciesInfo.ToDictionary(x => x.id, x => x.name);
                mcObj.Set<Dictionary<long, string?>>("speciesinfo", speciesinfoDict);
            }
            else
            {
                if (speciesinfoDict == null)
                    speciesinfoDict = mcObj.Get<Dictionary<long, string?>>("speciesinfo");
            }
        }

        public JsonSerializerSettings formatSettings = new JsonSerializerSettings
        {
            Formatting = Formatting.None,
            DateFormatString = "yyyy-MM-dd HH:mm:ss"
        };

        //删除宠物信息旧文件
        public void DeleteOldFile<T>(T tObj, string imgPath, string videoPath,bool isDeleteVideo=true)
        {
            string coverimgsrc = null;
            string videosrc = null;
            string otherimgsrc = null;

            if (tObj is PetInfo || tObj is AboutUS || tObj is PetStory || tObj is PetKnowledge)
            {
                Type t = tObj.GetType();
                PropertyInfo[] propertyList = t.GetProperties();

                PropertyInfo coverimgsrcProp = propertyList.Where(x => x.Name == "coverimgsrc").FirstOrDefault();
                coverimgsrc = coverimgsrcProp.GetValue(tObj, null) == null ? null : coverimgsrcProp.GetValue(tObj, null).ToString();

                PropertyInfo videosrcProp = propertyList.Where(x => x.Name == "videosrc").FirstOrDefault();
                videosrc = videosrcProp.GetValue(tObj, null) == null ? null : videosrcProp.GetValue(tObj, null).ToString();

                PropertyInfo otherimgsrcProp = propertyList.Where(x => x.Name == "otherimgsrc").FirstOrDefault();
                otherimgsrc = otherimgsrcProp.GetValue(tObj, null) == null ? null : otherimgsrcProp.GetValue(tObj, null).ToString();
            }
            else if (tObj is PetFosterage)
            {
                PetFosterage petFos = tObj as PetFosterage;
                videosrc = petFos.videosrc;
                otherimgsrc = petFos.imgsrcs;
            }

            if (!string.IsNullOrEmpty(coverimgsrc))
            {
                System.IO.File.Delete(imgPath + "/" + coverimgsrc);
            }

            if (isDeleteVideo && !string.IsNullOrEmpty(videosrc))
            {
                System.IO.File.Delete(videoPath + "/" + videosrc);
            }

            if (!string.IsNullOrEmpty(otherimgsrc))
            {
                string[] imgurls = otherimgsrc.Split('|');
                foreach (string url in imgurls)
                {
                    System.IO.File.Delete(imgPath + "/" + url);
                }
            }
        }

        //保存form文件
        public async Task<Dictionary<string, string>> SaveFormFiles(string imgPath, string videoPath, HttpRequest Request)
        {
            string coverImgSrc = "";
            string videoSrc = "";
            string otherImgSrc = "";

            //过form表单对象获取文件
            for (int i = 0; i < Request.Form.Files.Count; i++)
            {
                string filekey = Request.Form.Files[i].Name;//key值
                string fileOriginalName = Request.Form.Files[i].FileName;
                string newFileName = Guid.NewGuid().ToString() + fileOriginalName.Substring(fileOriginalName.LastIndexOf('.')).ToLower();//新名称

                if (filekey.Contains("coverImg"))
                    coverImgSrc = newFileName;
                else if (filekey.Contains("video"))
                    videoSrc = newFileName;
                else if (filekey.Contains("otherImg"))
                    otherImgSrc += (newFileName + "|");

                string pathInfo = "";
                if (filekey.Contains("video"))
                    pathInfo = videoPath;
                else
                    pathInfo = imgPath;

                using (var targetStream = System.IO.File.Create(pathInfo + "/" + newFileName))
                {
                    await Request.Form.Files[i].CopyToAsync(targetStream);
                }
            }

            if (otherImgSrc != "")
                otherImgSrc = otherImgSrc.Substring(0, otherImgSrc.Length - 1);

            Dictionary<string, string> fileSrcDict = new Dictionary<string, string>();
            fileSrcDict.Add("coverImgSrc", coverImgSrc);
            fileSrcDict.Add("videoSrc", videoSrc);
            fileSrcDict.Add("otherImgSrc", otherImgSrc);

            return fileSrcDict;
        }

        //产生不重复的随机数
        public IEnumerable<int> GenerateNoDuplicateRandom(int minValue, int maxValue)
        {
            //用C#3.0新增的Linq技术中的OrderBy方法排序，排序的依据是与原序列元素对应生成的一个“键”
            //Grid.NewGuid()方法返回的一个随机32位不重复Guid字符串。因为每次生成的Guid字符串大小都不同，
            //    且大小与生成先后无关，所以按这个“键”排序后的整数序列的顺序是随机的
            return Enumerable.Range(minValue, maxValue).OrderBy(g => Guid.NewGuid());
            //return Enumerable.Range(minValue, maxValue).ToList();//顺序产生数字
        }
    }
}
